package com.example.demon.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demon.dao.UserDao;
import com.example.demon.entity.Admin;
import com.example.demon.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;


@Service
@Transactional(rollbackFor = Exception.class)
public class UserService {

    @Autowired
    UserDao userDao;

    /**
     * 插入一位用户
     * @param openid
     * @param sex
     * @param name
     * @param avatar
     * @param phoneNumber
     * @return
     */
    public String saveAUser(String openid,String sex,String name,String avatar,String phoneNumber){
        User user = selectAUserByOpenid(openid);

        try {
            if (user!=null){
                user.setName(name);
                user.setAvatarUrl(avatar);
                user.setPhone(phoneNumber);
                user.setOpenid(openid);
                user.setSex(sex);
                userDao.updateById(user);
            }else {
                userDao.insert(User.builder()
                        .name(name)
                        .avatarUrl(avatar)
                        .openid(openid)
                        .phone(phoneNumber)
                        .sex(sex).build()
                );
            }

            return "success";
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "error";
        }
    }

    /**
     * 根据openid查找一位用户
     * @param openid
     * @return
     */
    public User selectAUserByOpenid(String openid){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("open_id", openid);
        return userDao.selectOne(queryWrapper);
    }



}
